package com.poker.controller;

import com.poker.consts.Consts;
import com.poker.entity.Banner;
import com.poker.service.BannerService;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: yuanZ;
 * @Date: 2018/10/13 15:08;
 * @Description: ;
**/
@Controller
@RequestMapping("/banner")
public class BannerController extends BaseController {

    @Resource
    private BannerService bannerService;

    @RequestMapping("/list")
    public String list(Model model, Banner banner,
                       @RequestParam(defaultValue = "0") Integer page,
                       @RequestParam(defaultValue = "20") Integer size) {
        Page<Banner> data = bannerService.findBannerNoCriteria(page, size);

        model.addAttribute("data", data);
        model.addAttribute("banner", banner);
        return managerPage("banner/list");
    }

    @RequestMapping("/edit")
    public String edit(Model model, String id, String editType) {
        Banner banner = new Banner();

        if (Consts.EditType.EDIT.equals(editType)) banner = bannerService.getById(id);
        model.addAttribute("banner",  banner);
        model.addAttribute("editType", editType);
        return managerPage("banner/edit");
    }

    @ResponseBody
    @RequestMapping("/add")
    public String add(Banner banner) {
        if (Misc.isEmpty(banner)) return toJson(false, "保存信息为空", null);

        Banner oldBanner = bannerService.getBySequence(banner.getSequence());
        if (!Misc.isEmpty(oldBanner)) return toJson(false, "当前序号已存在", null);
        banner.setCreateTime(new Date());
        bannerService.save(banner);

        return toJson(true, "success", null);
    }

    @RequestMapping("/delete")
    public String delete(String id, Integer page) {

        if (Misc.isEmpty(id)) return toJson(false, "id信息为空", null);

        Banner banner = bannerService.getById(id);
        if (Misc.isEmpty(banner)) return toJson(false, "banner信息为空", null);

        bannerService.delete(banner);

        return redirect("/banner/list?page=" + page);
    }

}
